const app = getApp()
const http = require('../../../utils/util')
const Base64 = require('../../../utils/base')
const localData = require("../../../utils/localData")
const time_data = require('../../../utils/data')
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		showHite:'none',
		second:0, //倒计时跳转
		interval:false, //
		conduct:'', //自习室守则内容
		seatRule:'none', //自习室守则
		
		room_params: {}, //上个页面传递过来的数据
		roomList: [], //会议室列表数据
		roomIndex: -1,
		all_date: '', //时间信息
		timeList: [],
		newTimeList: [],
		list:[],
		room:'',
		
		room_name:'', //正在占用的会议室名称
		hold_time:[], //占用会议室预约时间
	},

	//获取会议室列表数据
	getRoomData() {
		let data = {
			user_id: wx.getStorageSync('user_id'),
			user_token: wx.getStorageSync('user_token'),
			store_id: this.data.room_params.store_id,
			make_start_time: this.data.pickerDate,
			make_end_time: this.data.pickerDate,
			start_time: this.data.start_hours + ':00',
			end_time: this.data.end_hours + ':00'
		}
		http.post('store/roomL', Base64.encode(JSON.stringify(data))).then((res) => {
			if (res.status == 1) {
				this.setData({
					roomList: res.result
				})
			} else {
				wx.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		})
	},
	//选择日期选择器
	bindDateChange(e) {
		//清除之前选择的会议室状态
		this.setData({
			room:'',
			roomIndex:-1
		})
		
		let shop_start_MS = new Date(this.data.room_params.start_date).getTime()
		let current_MS = new Date(e.detail.value).getTime()
		if (current_MS > shop_start_MS) {
			let shop_start_time=this.data.room_params.shop_start_time
			let date = e.detail.value + ' ' + shop_start_time
			let hours=shop_start_time.split(':')[0].toString().length==1?'0'+shop_start_time.split(':')[0]:shop_start_time.split(':')[0]
			let minute=shop_start_time.split(':')[1].toString().length==1?'0'+shop_start_time.split(':')[1]:shop_start_time.split(':')[1]
			let start_hours=hours+':'+minute
			this.setData({
				pickerDate: e.detail.value,
				start_hours: start_hours,
				end_hours: time_data.new_hours(date).end_time,
			}, () => {
				this.getRoomData()
				this.filterPrickHours(start_hours)
			})
		} else {
			let timelist = this.data.timeList
			let shop_start = this.data.room_params.shop_start_time
			let start = time_data.new_hours().start_time
			let end = this.data.room_params.end_hours
			let startIndex = null
			let endIndex = null
			let shopStartIndex = null
			timelist.forEach((item, index) => {
				if (item == start) {
					startIndex = index
				}
				if (item == end) {
					endIndex = index
				}
				if (item == shop_start) {
					shopStartIndex = index
				}
			})
			if (startIndex >= endIndex) {
				return this.setData({
					pickerDate: e.detail.value,
					newTimeList: [],
					start_hours: this.data.room_params.shop_end_time,
					end_hours: this.data.room_params.shop_end_time,
					["list[0]"]:[],
					["list[1]"]:[],
				}, () => {
					this.getRoomData()
					this.filterPrickHours(this.data.room_params.shop_end_time)
				})
			} 
			
			if (startIndex < shopStartIndex) {
				let date=this.data.room_params.start_date+' '+shop_start
				return this.setData({
					pickerDate: e.detail.value,
					newTimeList: timelist.slice(shopStartIndex, endIndex + 1),
					start_hours: shop_start,
					end_hours: time_data.new_hours(date).end_time,
					["list[0]"]:timelist.slice(shopStartIndex, endIndex + 1),
					["list[1]"]:timelist.slice(shopStartIndex+1, endIndex + 1),
				}, () => {
					this.getRoomData()
					this.filterPrickHours(shop_start)
				})
			}
			
			this.setData({
				pickerDate: e.detail.value,
				newTimeList: timelist.slice(startIndex, endIndex + 1),
				start_hours: time_data.new_hours().start_time,
				end_hours: time_data.new_hours().end_time,
				["list[0]"]:timelist.slice(startIndex, endIndex + 1),
				["list[1]"]:timelist.slice(startIndex+1, endIndex + 1),
			}, () => {
				this.getRoomData()
				this.filterPrickHours(this.data.room_params.start_hours)
			})
		}
	},

	//选择会议室
	changeRoom(e) {
		let index = e.currentTarget.dataset.index
		let room = this.data.roomList[index]
		//判断check是否为1，为1时他人占用不能点击
		if(room.check==1){
			
			this.setData({
				room_name:room.room_name
			})
			let data={
				rid:room.rid
			}
			http.post('store/roomTime', Base64.encode(JSON.stringify(data))).then(res=>{
				if(res.status==1){
					this.setData({
						hold_time:res.result
					})
				}else{
					wx.showToast({
						title:res.message,
						icon:'none'
					})
				}
			})
			
			//弹窗
			this.setData({
				showHite:'show'
			})
			return
		}
		
		this.setData({
			roomIndex: index,
			room:room
		})
	},
	//隐藏灰色座位弹出层
	hitehide(){
		this.setData({
			showHite: 'hide'
		})
		setTimeout(() => {
			this.setData({
				showHite: 'none'
			})
		}, 200)
	},
	//隐藏自习室守则
	hideSeatRule(){
		this.setData({
			interval:true,
			seatRule:'none'
		})
		this.setData({
			seatRule: 'hide'
		})
		setTimeout(() => {
			this.setData({
				seatRule: 'none'
			})
		}, 200)
	},
	
	// 监听 “确认预约” 按钮组件的回调
	onMakeBtnEvent() {
		//判断用户是否登录
		let _this = this
		let user_token = wx.getStorageSync('user_token')
		if (!user_token) {
			wx.showModal({
				title: '提示',
				content: '你还没有登陆，是否登录?',
				success(res) {
					if (res.confirm) {
						wx.clearStorageSync()
						_this.login()
					}
				}
			})
			return
		}

		// 判断当前是否有选中的会议室
		let room = this.data.roomList[this.data.roomIndex]
		if (!room) {
			wx.showToast({
				title: '请选择会议室',
				icon: 'none'
			})
			return
		}
		
		//判断选中的会议室是否被占用
		if(room.check==1){
			wx.showToast({
				title: '该会议室已被占用,请选择其他会议室',
				icon: 'none'
			})
			return
		}


		//判断用户选择时间段
		let s=this.data.pickerDate + ' ' + this.data.start_hours
		let e=this.data.pickerDate + ' ' + this.data.end_hours
		let start_MS = new Date(s.replace(/-/g,'/')).getTime()
		let end_MS = new Date(e.replace(/-/g,'/')).getTime()
		let small_m=this.data.room.minutes*60*1000  //最小预约毫秒数
		
		if(end_MS<=start_MS){
			return wx.showToast({
				title: `结束时间不能小于开始时间`,
				icon: 'none'
			})
		}
		if ((end_MS - start_MS) < small_m) {
			return wx.showToast({
				title: `预约时间不能低于${this.data.room.minutes}分钟`,
				icon: 'none'
			})
		}
		
		//订阅消息授权
		// wx.requestSubscribeMessage({
		// 	tmplIds:['ig9l3u4D9mShf6ZxHwl7tBnrskYbh84jyCNF8SzvHfc'],
		// 	complete:()=>{
		// 		this.roomRules()
		// 	}
		// })
		this.roomRules()
		
	},
	//判断是否弹出自定义守则，去往提交订单页面
	roomRules(){
		//判断是否弹出自定义守则
		let params={
			user_id:wx.getStorageSync('user_id'),
			user_token:wx.getStorageSync('user_token'),
			store_id:this.data.room_params.store_id
		}
		http.post('store/stipulate', Base64.encode(JSON.stringify(params))).then(res=>{
			if(res.status==1){
				if(res.result.status==0){
					if(!res.result.conduct){  //自习室守则内容为空时,不弹出提示框直接进入提交订单页
						this.setData({
							second:0
						})
						//去往提交订单页
						this.navigateSubOrder()
						return
					}
					this.setData({
						seatRule:'show',
						conduct:res.result.conduct
					},()=>{
						let interval= setInterval(()=>{
							if(this.data.interval || this.data.second<=0){
								clearInterval(interval)
							}
							this.setData({
								second: --this.data.second
							})
						},1000)
					})
				}else{
					this.setData({
						second:0
					})
					//去往提交订单页
					this.navigateSubOrder()
				}
			}else{
				wx.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		})
	},
	//乘法计算精度
	accMul(arg1,arg2) 
	 { 
	 var m=0,s1=arg1.toString(),s2=arg2.toString(); 
	 try{m+=s1.split(".")[1].length}catch(e){} 
	 try{m+=s2.split(".")[1].length}catch(e){} 
	 return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) 
	 },
	//去往提交订单
	navigateSubOrder(){
		//倒计时10s内点击无效不做跳转
		if(this.data.second>0) return
		
		this.setData({
			interval:true,
			seatRule:'none'
		})
		
		let room = this.data.roomList[this.data.roomIndex]
		let s=this.data.pickerDate + ' ' + this.data.start_hours
		let e=this.data.pickerDate + ' ' + this.data.end_hours
		let start_MS = new Date(s.replace(/-/g,'/')).getTime()
		let end_MS = new Date(e.replace(/-/g,'/')).getTime()
		//共计多少小时
		let hours = (end_MS - start_MS) / 3600000
		//预计费用
		let subtotal = this.accMul(room.price,hours)
		// 星期几
		let week=new Date(this.data.pickerDate.replace(/-/g,'/')).getDay()
		switch (week){
			case 0:
				week='周日'
				break
			case 1:
				week='周一'
				break
			case 2:
				week='周二'
				break
			case 3:
				week='周三'
				break
			case 4:
				week='周四'
				break
			case 5:
				week='周五'
				break
			case 6:
				week='周六'
				break
		}
		let data = {
			predict_price: room.price, //预估费用
			shop_name: 'xxx',
			shop_address: 'xxx',
			store_id: this.data.room_params.store_id, // 门店id
			date: this.data.pickerDate, //预约日期
			start_hours: this.data.start_hours, //预约开始时间
			end_hours: this.data.end_hours, //预约结束时间
			hours: hours,
			subtotal: subtotal, //小计
			room: room,
			store_money:this.data.room_params.store_money,
			weekday:week
		}
		//带参数跳转
		wx.navigateTo({
			url: '/pages/store/roomorder/roomorder?room=' + JSON.stringify(data)
		})
	},
	//登录
	login() {
		wx.login({
			success(res) {
				if (res.code) {
					wx.setStorageSync('code', res.code)
				} else {}
			}
		})
		const _this = this
		wx.getUserProfile({
			desc: '获取用户相关信息',
			success: function(obj) {
				console.log(wx.getStorageSync('code'))
				let code = wx.getStorageSync('code')
				var data = {
					code: code,
					encryptedData: obj.encryptedData,
					iv: obj.iv,
				}
				http.post('wechat/login', Base64.encode(JSON.stringify(data))).then(res => {
					if (res.status != 1) {}
					wx.setStorageSync('user_id', res.result.user_id)
					wx.setStorageSync('user_token', res.result.user_token)
					wx.setStorageSync('phone', res.result.phone)
					wx.showToast({
						title: '登录成功',
						icon: 'none'
					})
				})
			},
			fail: function(obj) {}
		})
	},
	//筛选时间选择器时间段
	filterPrickHours(start_hours) {
		let timelist = this.data.timeList
		let start = start_hours
		let end = this.data.room_params.shop_end_time
		let startIndex = null
		let endIndex = null
		this.data.timeList.forEach((item, index) => {
			if (item == start) {
				startIndex = index
			}
			if (item == end) {
				endIndex = index
			}
		})
		this.setData({
			newTimeList: timelist.slice(startIndex, endIndex + 1),
			["list[0]"]:timelist.slice(startIndex, endIndex + 1),
			["list[1]"]:timelist.slice(startIndex+1, endIndex + 1),
		})
	},

	//多列选择器
	multiSelector(e){
		//清除之前选择的会议室状态
		this.setData({
			room:'',
			roomIndex:-1
		})
		let start_index=e.detail.value[0]
		let end_index=e.detail.value[1]
		let start_hours=this.data.list[0][start_index]
		let end_hours=this.data.list[1][end_index]
		this.setData({
			start_hours:start_hours,
			end_hours:end_hours
		},()=>{
			this.getRoomData()
		})
	},
	//列改变时触发
	columnchange(e){
		let list=this.data.list[0]
		let index=e.detail.value
		if(e.detail.column==0){ //左边选择列在动
			if(list.length==index+1){
				this.setData({
					['list[1]']:list.slice(index)
				})
			}else{
				this.setData({
					['list[1]']:list.slice(index+1)
				})
			}
		}
	},
	//去相册
	tophoto(e){
		let params={
			room_id:e.currentTarget.dataset.roomid,
			store_id:this.data.room_params.store_id
		}
		wx.navigateTo({
			url: '/pages/mine/atlas/atlas?params=' + JSON.stringify(params)
		})
	},



	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		let room_params = JSON.parse(options.room_params)
		this.setData({
			timeList: localData.timeList,
			room_params: room_params,
			pickerDate: room_params.currentDate,
			start_hours: room_params.start_hours,
			end_hours: room_params.end_hours
		})
		this.getRoomData()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {
		this.filterPrickHours(this.data.room_params.start_hours)
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		let appdate = app.globalData
		this.setData({
			all_date: appdate
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
